﻿using System;
using System.Data;
using System.Collections.Generic;
using YiYiTong.Rocket.Helper;
using YiYiTong.Rocket.Entity;
using YiYiTong.Rocket.Model;
using YiYiTong.Rocket.DataAccess;
using YiYiTong.Rocket.EFDBFirst;
using System.Web;
using System.Linq;

namespace YiYiTong.Rocket.Business
{
    public class GoodsBiz
    {
        #region 单例模式
        private GoodsBiz()
        {
        }

        private static GoodsBiz _instance;
        private static readonly object _syncObject = new object();

        public static GoodsBiz Instance
        {
            get
            {
                if (_instance == null)
                {
                    lock (_syncObject)
                    {
                        if (_instance == null)
                        {
                            _instance = new GoodsBiz();
                        }
                    }
                }
                return _instance;
            }
        }
        #endregion 单例模式

        /// <summary>
        /// 品牌列表
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, BrandModel> GetBrandList(long brand_category, string brand_name, string brand_name_en, long category_id, int pageIndex, int pageRows)
        {
            DataSet ds = GoodsDataAccess.Instance.GetBrandList(brand_category, brand_name, brand_name_en, category_id, pageIndex, pageRows);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                BrandModel model = new BrandModel();
                model.list = new ModelHandler<BrandInfo>().FillModel(ds.Tables[1]);
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);

                //处理图片
                foreach (var item in model.list)
                {
                    string logimgurl = item.logo_img_url.ToLower();
                    if (!string.IsNullOrWhiteSpace(logimgurl) && !(logimgurl.StartsWith("http://") || logimgurl.StartsWith("https://")))
                        item.logo_img_url = AliyunOssBiz.GetImg(item.logo_img_url);
                }
                return new Tuple<bool, BrandModel>(true, model);
            }
            else
                return new Tuple<bool, BrandModel>(false, null);
        }

        /// <summary>
        /// 新增品牌
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> AddBrand(ADZ_BrandMaster brand)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();

            //设置默认值
            brand.is_del = 0;
            brand.create_time = DateTime.Now;
            brand.brand_category = 0;

            HttpFileCollection hfc = HttpContext.Current.Request.Files;
            if (hfc != null && hfc.Count > 0)
            {
                var file = hfc[0];
                var putResult = ImageFileBiz.UpImg(file);
                if (!putResult.Item1)
                    return new Tuple<bool, string>(false, putResult.Item2);
                else
                    brand.logo_img_url = putResult.Item3;
            }
            //else
            //    return new Tuple<bool, string>(false, "请上传图片");

            //验证品牌名称重复
            var entity = dbcontext.ADZ_BrandMaster.FirstOrDefault(t => t.brand_name == brand.brand_name && t.is_del == 0);
            if (entity != null)
                return new Tuple<bool, string>(false, "品牌名称已存在");

            dbcontext.ADZ_BrandMaster.Add(brand);
            dbcontext.SaveChanges();
            return new Tuple<bool, string>(true, "新增成功");
        }

        /// <summary>
        /// 编辑品牌
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, string> EditBrand(ADZ_BrandMaster brand)
        {
            ADZ_MasterEntities dbcontext = new ADZ_MasterEntities();
            if (brand.brand_id > 0)
            {
                var entity = dbcontext.ADZ_BrandMaster.FirstOrDefault(t => t.brand_id == brand.brand_id && t.is_del == 0);
                if (entity == null)
                    return new Tuple<bool, string>(false, "品牌不存在");

                if (entity.brand_name != brand.brand_name)
                {
                    if (dbcontext.ADZ_BrandMaster.FirstOrDefault(t => t.brand_name == brand.brand_name && t.is_del == 0) != null)
                        return new Tuple<bool, string>(false, "品牌名称已存在");
                }

                entity.brand_name = brand.brand_name;
                entity.brand_name_en = brand.brand_name_en;
                entity.is_show = brand.is_show;
                entity.brand_content = brand.brand_content;

                HttpFileCollection hfc = HttpContext.Current.Request.Files;
                if (hfc != null && hfc.Count > 0)
                {
                    var file = hfc[0];
                    var putResult = ImageFileBiz.UpImg(file);
                    if (!putResult.Item1)
                        return new Tuple<bool, string>(false, putResult.Item2);
                    else
                        entity.logo_img_url = putResult.Item3;
                }
                else
                {
                    //if (string.IsNullOrWhiteSpace(brand.logo_img_url))
                    //   return new Tuple<bool, string>(false, "请上传图片");
                }

                dbcontext.SaveChanges();
                return new Tuple<bool, string>(true, "编辑成功");
            }
            else
                return new Tuple<bool, string>(false, "品牌不存在");
        }

        /// <summary>
        /// 商品分类
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, List<GoodsCategory>> GetCategory(long brand_id)
        {
            DataTable dt = GoodsDataAccess.Instance.GetCategory(brand_id);
            if (dt != null && dt.Rows.Count > 0)
            {
                List<GoodsCategory> list = new ModelHandler<GoodsCategory>().FillModel(dt, false, false);
                return new Tuple<bool, List<GoodsCategory>>(true, list);
            }
            else
                return new Tuple<bool, List<GoodsCategory>>(false, null);
        }

        /// <summary>
        /// 生成商品分类的编码
        /// level 分层的级别,顶级分类（根分类）为1，二级分类为2，依次类推
        /// </summary>
        public Tuple<bool, string> BuildCategoryCode(long category_id, int level)
        {
            if (category_id <= 0 || level <= 0)
                return new Tuple<bool, string>(false, "");

            string code = string.Empty;
            if (GoodsDataAccess.Instance.BuildCategoryCode(category_id, level, out code) > 0)
                return new Tuple<bool, string>(true, code);
            else
                return new Tuple<bool, string>(false, "");
        }

        /// <summary>
        /// 商品查询
        /// </summary>
        /// <param name="label_type">1 直播 2 预热 3 爆款</param>
        /// <param name="brand_id">品牌id</param>
        /// <param name="category_id">分类id</param>
        /// <param name="selKey">搜索关键字</param>
        /// <returns></returns>
        public Tuple<bool, GoodsListModel> GetList(long uid, int label_type, long brand_id, long category_id, string selKey, int pageIndex, int pageRows,int is_withdraw, long supplier_id,int base_label_type)
        {
            DataSet ds = GoodsDataAccess.Instance.GetGoodsList(uid, label_type, brand_id, category_id, selKey, pageIndex, pageRows, is_withdraw, supplier_id, base_label_type);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                GoodsListModel model = new GoodsListModel();
                model.list = new ModelHandler<GoodsModel>().FillModel(ds.Tables[1]);
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);

                foreach (var item in model.list)
                {
                    //处理是否最新上架 2019-05-30 leev
                    item.is_new = CheckNew(item.with_up_time) ? 1 : 0;
                    //处理图片
                    item.imglist = GetGoodsIMG(item.goods_id);
                    //处理预热商品报价
                    if (label_type == (int)LabelType.YuRe)
                    {
                        var result = OrderBiz.Instance.GetGoodsPlace(uid, item.goods_id);
                        if (result.Item3 != "3")
                        {
                            item.place_price = result.Item2;
                        }
                    }
                }

                return new Tuple<bool, GoodsListModel>(true, model);
            }
            else
                return new Tuple<bool, GoodsListModel>(false, null);
        }

        /// <summary>
        /// 检查商品是否最新上架
        /// </summary>
        /// <returns></returns>
        private bool CheckNew(DateTime d)
        {
            DateTime com_date = ConvertHelper.ConvertTo<DateTime>(DateTime.Now.ToString("yyyy-MM-dd"));
            if (d == null || d == DateTime.MinValue)
                d = ConvertHelper.ConvertTo<DateTime>("1900-01-01");
            else
                d= ConvertHelper.ConvertTo<DateTime>(d.ToString("yyyy-MM-dd"));

            if (com_date == d)
                return true;
            else
                return false;
        }


        /// <summary>
        /// 获取批量转发商品列表
        /// </summary>
        /// <param name="label_type">1 直播 2 预热 3 爆款</param>
        /// <param name="brand_id">品牌id</param>
        /// <param name="category_id">分类id</param>
        /// <param name="selKey">搜索关键字</param>
        /// <returns></returns>
        public Tuple<bool, GoodsListModel> GetBatchList(long uid, int label_type, long brand_id, long category_id, string selKey, int pageIndex, int pageRows,int base_label_type)
        {
            DataSet ds = GoodsDataAccess.Instance.GetGoodsBacthList(uid, label_type, brand_id, category_id, selKey, pageIndex, pageRows, base_label_type);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                GoodsListModel model = new GoodsListModel();
                model.list = new ModelHandler<GoodsModel>().FillModel(ds.Tables[1]);
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);

                foreach (var item in model.list)
                {
                    //处理图片
                    item.imglist = GetGoodsIMG(item.goods_id);
                    //处理预热商品报价
                    if (label_type == (int)LabelType.YuRe)
                    {
                        var result = OrderBiz.Instance.GetGoodsPlace(uid, item.goods_id);
                        item.place_price = result.Item2;
                    }
                }

                return new Tuple<bool, GoodsListModel>(true, model);
            }
            else
                return new Tuple<bool, GoodsListModel>(false, null);
        }

        /// <summary>
        /// 商品详情
        /// </summary>
        public Tuple<bool, GoodsModel> GetInfo(long uid, long goods_id)
        {
            DataTable dt = GoodsDataAccess.Instance.GetGoods(goods_id);
            if (dt != null && dt.Rows.Count > 0)
            {
                GoodsModel goods = new ModelHandler<GoodsModel>().FillModel(dt.Rows[0], false, false);

                //商品已下架不能获取详情
                if (ConvertHelper.ConvertTo<int>(dt.Rows[0]["is_withdraw"], 0) != 0)
                    return new Tuple<bool, GoodsModel>(false, null);
                //商品无库存不能获取详情
                if (goods.stock_amount <= 0)
                    return new Tuple<bool, GoodsModel>(false, null);

                //商品抢购结束不能获取详情
                if (goods.end_time != DateTime.MinValue)
                {
                    if (goods.end_time.CompareTo(DateTime.Now) < 0)
                        return new Tuple<bool, GoodsModel>(false, null);
                }

                //处理是否最新上架 2019-05-30 leev
                goods.is_new = CheckNew(goods.with_up_time) ? 1 : 0;
                //处理图片
                goods.imglist = GetGoodsIMG(goods_id);
                //处理预热商品报价
                if (goods.label_type == (int)LabelType.YuRe)
                {
                    var result = OrderBiz.Instance.GetGoodsPlace(uid, goods_id);
                    goods.place_price = result.Item2;
                }
                return new Tuple<bool, GoodsModel>(true, goods);
            }
            else
                return new Tuple<bool, GoodsModel>(false, null);
        }

        /// <summary>
        /// 获取头像
        /// </summary>
        /// <param name="goods_id"></param>
        /// <returns></returns>
        public List<GoodsIMG> GetGoodsIMG(long goods_id, bool is_one = false)
        {
            List<GoodsIMG> list = new List<GoodsIMG>();
            DataTable dt = GoodsDataAccess.Instance.GetGoodsIMG(goods_id, is_one);
            if (dt != null && dt.Rows.Count > 0)
            {
                for (int i = 0; i < dt.Rows.Count; i++)
                {
                    GoodsIMG img = new GoodsIMG();
                    img.img_url = AliyunOssBiz.GetImg(dt.Rows[i]["img_url"].ToString());
                    list.Add(img);
                }
            }
            else
            {
                GoodsIMG img = new GoodsIMG();
                img.img_url = ConfigHelper.AppSetting<string>("good_imgurl");
                list.Add(img);
            }
            return list;
        }

        /// <summary>
        /// 获取商品
        /// </summary>
        /// <param name="goods_id"></param>
        /// <returns></returns>
        public Tuple<bool, GoodsModel> GetGoods(long goods_id)
        {
            if (goods_id <= 0)
                return new Tuple<bool, GoodsModel>(false, null);

            DataTable dt = GoodsDataAccess.Instance.GetGoods(goods_id);
            if (dt != null && dt.Rows.Count > 0)
            {
                GoodsModel model = new ModelHandler<GoodsModel>().FillModel(dt.Rows[0], false, false);
                return new Tuple<bool, GoodsModel>(true, model);
            }
            else
                return new Tuple<bool, GoodsModel>(false, null);
        }

        /// <summary>
        /// 增加库存
        /// </summary>
        public bool AddStockAmount(long goods_id, decimal amount)
        {
            if (goods_id <= 0 || amount <= 0)
                return false;

            var result = GetGoods(goods_id);
            if (result.Item1)
            {
                int ret = GoodsDataAccess.Instance.AddStockAmount(goods_id, amount);
                if (ret > 0)
                    return true;
                else
                    return false;
            }
            else
                return false;
        }

        /// <summary>
        /// 商品转发记录
        /// </summary>
        public Tuple<bool, string> Forward(long uid, string goods_ids, int device_type, string remark)
        {
            if (goods_ids.EndsWith(","))
                goods_ids = goods_ids.Substring(0, goods_ids.Length - 1);
            var goodsList = StringHelper.Split(goods_ids, ',');
            if (goodsList.Count() == 0)
                return new Tuple<bool, string>(false, "转发商品为空");

            bool valid_goods = true;
            List<long> goods_id_list = new List<long>();
            foreach (var item in goodsList)
            {
                long goods_id = ConvertHelper.ConvertTo<long>(item);
                var goods = GetGoods(goods_id);
                if (goods == null)
                {
                    valid_goods = false;
                    break;
                }
                else
                    goods_id_list.Add(goods_id);
            }

            if (!valid_goods)
                return new Tuple<bool, string>(false, "转发商品不存在");

            string stroutput = string.Empty;
            bool is_succ = false;
            if (goods_id_list.Count != 0)
            {
                string batch = DateTime.Now.ToString("yyyyMMddHHmmssfff");
                foreach (var item2 in goods_id_list)
                {
                    if (GoodsDataAccess.Instance.Forward(item2, uid, device_type, batch, remark, out stroutput) > 0)
                        is_succ = true;
                }

                if (is_succ)
                    return new Tuple<bool, string>(true, "");
                else
                    return new Tuple<bool, string>(false, stroutput);
            }
            else
                return new Tuple<bool, string>(false, "转发商品为空");
        }

        /// <summary>
        /// 商品转发统计
        /// </summary>
        /// <returns></returns>
        public Tuple<bool, ForwardTongJiList> ForwardTongJi(long supplier_id, long brand_id, long category_id, string beg_date, string end_date, int pageIndex, int pageRows)
        {
            if (!string.IsNullOrEmpty(end_date))
                end_date = ConvertHelper.ConvertTo<DateTime>(end_date).AddDays(1).ToString("yyyy-MM-dd");

            DataSet ds = GoodsDataAccess.Instance.ForwardTongJi(supplier_id, brand_id, category_id, beg_date, end_date, pageIndex, pageRows);
            if (ds != null && ds.Tables.Count > 0 && ds.Tables[1].Rows.Count > 0)
            {
                ForwardTongJiList model = new ForwardTongJiList();
                model.allrows = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allrows"]);
                model.allpages = ConvertHelper.ConvertTo<int>(ds.Tables[0].Rows[0]["allpages"]);
                model.list = new ModelHandler<ForwardTongJi>().FillModel(ds.Tables[1]);

                return new Tuple<bool, ForwardTongJiList>(true, model);
            }
            else
                return new Tuple<bool, ForwardTongJiList>(false, null);
        }
    }
}
